package com.atguigu.spzx.manger.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.manger.mapper.SysUserMapper;
import com.atguigu.spzx.manger.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.service.exception.GuiguException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {

        //校验验证码
        //获取reids存储key
        String codeKey = loginDto.getCodeKey();
        //获取用户输入的验证码
        String inputCaptcha = loginDto.getCaptcha();
        //从reids中获取验证码
        String redisCaptcha = redisTemplate.opsForValue().get("user:login:validateCode:" + codeKey);
        //比较
        if( StrUtil.isEmpty(redisCaptcha)||!StrUtil.equalsIgnoreCase(inputCaptcha,redisCaptcha)){

            throw  new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //删除验证码
        redisTemplate.delete("user:login:validateCode:" + codeKey);
        //根据用户名查询
        SysUser user = sysUserMapper.selectSysUserByUserName(loginDto.getUserName());
        //判断
        if(user==null){

            throw  new GuiguException(ResultCodeEnum.LOGIN_ERROR);

        }


        //校验密码
        //获取用户输入明文密码
        String password = loginDto.getPassword();
        //加密
        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        //比较
        if(!md5InputPassword.equals(user.getPassword())){
//            throw  new RuntimeException("用户名或者密码错误~！！！");
            throw  new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //生成token DSAFDASFS-DFSAFDAS-FDSAFDSA-SFDA
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //存储到redis  结构： key     value: String   Object
        redisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(user),7, TimeUnit.DAYS);

        //封装数据响应
        LoginVo loginVo=new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        return loginVo;

    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @Override
    public SysUser getUserInfo(String token) {
        String strUser = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(strUser, SysUser.class);
        return sysUser;
    }

    /**
     * 用户退出
     * @param token
     */
    @Override
    public void loginOut(String token) {

        redisTemplate.delete("user:login:" + token);
    }

    /**
     * 条件分页查询用户
     * @param sysUserDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        //设置分页条件
        PageHelper.startPage(pageNum,pageSize);
        //查询用户列表
        List<SysUser> sysUserList=sysUserMapper.findByPage(sysUserDto);
        //封装分页对象
        return new PageInfo<>(sysUserList);
    }

    /**
     * 新增用户
     * @param sysUser
     */
    @Override
    public void saveSysUser(SysUser sysUser) {

        //判断是否存在新增的用户
        SysUser user = sysUserMapper.selectSysUserByUserName(sysUser.getUserName());
        if(user!=null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //密码加密
        String userPassword = sysUser.getPassword();
        //加密
        String password = DigestUtils.md5DigestAsHex(userPassword.getBytes());
        sysUser.setPassword(password);

        //状态赋值
        sysUser.setStatus(0);
        //新增
        sysUserMapper.saveSysUser(sysUser);

    }

    /**
     * 修改用户信息
     * @param sysUser
     */
    @Override
    public void updateSysUser(SysUser sysUser) {

        //判断
//        SysUser user = sysUserMapper.selectSysUserByUserName(sysUser.getUserName());
//        if(user!=null){
//            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
//        }
        //修改
        sysUserMapper.updateSysUser(sysUser);
    }

    /**
     * 根据id删除用户
     * @param userId
     */
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);

    }
}
